package gc.analyze;

public class Smooth {

	public static long[] smooth(long[] times, long window) {
		assert (times.length & 1) == 1 : times.length;

		long ta = 0;
		int ia = 0;
		int da = 0;
		long td = window;
		int id = 0;
		int dd = 0;
		long val = 0;
		long pt = 0;
		int dir = 0;

		long[] result = new long[(times.length + 1) * 4];
		int pos = 0;

		while (ta < Long.MAX_VALUE || td < Long.MAX_VALUE) {
			long tt;
			if (ta < td) {
				tt = ta;
				da = ia < times.length ? ia & 1 : 0;
				if (ia < times.length) {
					ta += times[ia];
					ia += 1;
				} else {
					ta = Long.MAX_VALUE;
				}
			} else {
				tt = td;
				dd = id < times.length ? id & 1 : 0;
				if (id < times.length) {
					td += times[id];
					id += 1;
				} else {
					td = Long.MAX_VALUE;
				}
			}
			val += dir * (tt - pt);
			dir = da - dd;
			result[pos++] = tt;
			result[pos++] = val;
			pt = tt;
		}

		assert result.length == pos : result.length + " == " + pos;
		return result;
	}

	public static int maxi(long[] smooth) {
		int xi = 0;
		for (int i = 2; i < smooth.length; i += 2) {
			if (smooth[i + 1] > smooth[xi + 1]) {
				xi = i;
			}
		} 
		return xi;
	}
}
